# import re
#
# def replace_single_number(line, new_number):
#     # 匹配开头编号：如 1.1.1 或 1.1.1.
#     match = re.match(r'^(\s*)(\d+(?:\.\d+)*)([.\s]+)(.*)', line)
#     if match:
#         indent, _, sep, title = match.groups()
#         return f"{indent}{new_number}{sep}{title}"
#     return line
#
# # 示例输入
# old_line = "1.1.1 相关方案的测试"
# new_number = "3.1.1"
#
# # 替换
# new_line = replace_single_number(old_line, new_number)
# print(new_line)
#
#
# def increment_any_number(number_str: str) -> str:
#     """
#     输入形如 '3'、'3.2'、'3.2.1' 的编号字符串，
#     返回最后一段数字递增1的新编号字符串。
#     """
#     if not number_str.strip():
#         return "1"
#     parts = number_str.strip().split(".")
#     try:
#         parts = [int(p) for p in parts]
#     except ValueError:
#         raise ValueError("编号中必须全部是数字组成，如 '1.2.3'")
#     parts[-1] += 1
#     return ".".join(str(p) for p in parts)
# # 测试示例
# if __name__ == "__main__":
#     tests = [
#         "1",
#         "2.1",
#         "2.1.9",
#         "3.0.0.9",
#         "10.5.4",
#         ""
#     ]
#
#     print(increment_any_number("1"))
#     for test in tests:
#         print(f"{test} -> {increment_any_number(test)}")

#
# def get_last_element(arr):
#     return arr[-1] if arr else None
#
# def delete_element(arr, value):
#     if value in arr:
#         arr.remove(value)
#     return arr
#
# def increment_section_number(section: str) -> str:
#     parts = section.strip().split(".")
#     parts[-1] = str(int(parts[-1]) + 1)
#     return ".".join(parts)
#
# # 示例数组
# arr = ["1.1.1", "2.2.2", "3.1.1"]
#
# # 获取最后一个
# last = get_last_element(arr)
# print("最后一个编号：", last)

# # 删除一个元素
# arr = delete_element(arr, "2.2.2")
# print("删除后的数组：", arr)
#
# # 编号递增
# new_number = increment_section_number("3.1.1")
# print("编号递增后：", new_number)

import re
from docx import Document

def remove_trailing_page_number(text: str) -> str:
    # 去掉结尾的“……123”或空格+数字（假设是页码）
    return re.sub(r'[\.。．…]*\s*\d{1,3}$', '', text.strip())

def convert_docx_to_md_clean(docx_path, output_md_path):
    doc = Document(docx_path)
    output = []

    for para in doc.paragraphs:
        raw_text = para.text.strip()
        if not raw_text:
            continue

        clean_text = remove_trailing_page_number(raw_text)

        style = para.style.name
        if style.startswith("Heading"):
            level = int(style.replace("Heading", "").strip() or 2)
            output.append(f"{'#' * level} {clean_text}")
        else:
            output.append(clean_text)

    with open(output_md_path, "w", encoding="utf-8") as f:
        f.write('\n'.join(output))

    print(f"✅ 转换完成，已去掉行尾页码，保存至：{output_md_path}")

# 使用示例
convert_docx_to_md_clean(
    "D:\\hbyt\\AI智能投标\\典型投标标书目录\\word\\常规目录\\投标文件-技术部分-天翼视联6.12终版.docx",
    "D:\\hbyt\\AI智能投标\\典型投标标书目录\\word\\常规目录\\投标文件-技术部分-天翼视联6.12终版.md"
)

# from docx import Document
# import os
#
# def convert_table_to_markdown(table):
#     rows = []
#     for row in table.rows:
#         cells = [cell.text.strip().replace('\n', ' ') for cell in row.cells]
#         rows.append(cells)
#
#     if not rows:
#         return ''
#
#     # 构建 markdown 表格
#     header = '| ' + ' | '.join(rows[0]) + ' |'
#     separator = '| ' + ' | '.join(['---'] * len(rows[0])) + ' |'
#     body = ['| ' + ' | '.join(row) + ' |' for row in rows[1:]]
#
#     return '\n'.join([header, separator] + body)
#
# def convert_docx_to_markdown_no_breaks(docx_path, output_md_path):
#     doc = Document(docx_path)
#     output = []
#
#     for para in doc.paragraphs:
#         text = para.text.strip()
#         style = para.style.name
#
#         if not text:
#             continue
#
#         if style.startswith("Heading"):
#             level = style.replace("Heading", "").strip()
#             level = int(level) if level.isdigit() else 2
#             output.append(f"{'#' * level} {text}")
#         else:
#             output.append(text)  # 段落不加空行，不换行
#
#     # 处理表格
#     for table in doc.tables:
#         output.append(convert_table_to_markdown(table))
#
#     # 合并输出为单个段落串
#     with open(output_md_path, "w", encoding="utf-8") as f:
#         f.write('\n'.join(output))  # 不添加多余换行
#
#     print(f"✅ 转换完成（无换行），保存为：{output_md_path}")
#
# # 使用示例
# convert_docx_to_markdown_no_breaks(
#     "D:\\hbyt\\AI智能投标\\典型投标标书目录\\word\\常规目录\\典型标书示例_金融研发_慧博_v1.0_20240401.docx",
#     "D:\\hbyt\\AI智能投标\\典型投标标书目录\\word\\常规目录\\典型标书示例_金融研发_慧博_v1.0_20240401.md"
# )


# import re
#
# def clean_directory(text):
#     cleaned_lines = []
#     for line in text.strip().splitlines():
#         # 去除末尾的制表符或空格 + 数字（如 tab+1，空格1，……1 等）
#         cleaned = re.sub(r'[\t\s]+1\s*$', '', line.strip())
#         cleaned_lines.append(cleaned)
#     return '\n'.join(cleaned_lines)
#
#
# with open("D:\\hbyt\\AI智能投标\\典型投标标书目录\\word\\常规目录\\典型标书示例_金融研发_慧博_v1.0_20240401.md", 'r', encoding='utf-8') as f:
#     content=f.read()
# # 示例使用
# raw_text = content
#
# cleaned_text = clean_directory(raw_text)
# print(cleaned_text)



